package com.concurrent.aqslock.part8.reent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 演示tryLock
 */
public class TryLockReenTrant {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] arg0) {
        Thread t1 = new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + " before try lock");
                if(lock.tryLock()){
                    Thread.sleep(3000);
                    System.out.println(Thread.currentThread().getName() + " after try lock");
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(lock.isHeldByCurrentThread()){
                    System.out.println(Thread.currentThread().getName()+" unlock");
                    lock.unlock();
                }
            }
        }, "first thread");

        Thread t2 = new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + " before try lock");
                if(lock.tryLock()){
                    Thread.sleep(2000);
                    System.out.println(Thread.currentThread().getName() + " after try lock");
                } else {
                    System.out.println(Thread.currentThread().getName() + " try lock fail");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(lock.isHeldByCurrentThread()){
                    System.out.println(Thread.currentThread().getName()+" unlock");
                    lock.unlock();
                }
            }
        }, "second thread");

        Thread t3 = new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + " before try lock");
                if(lock.tryLock(6L, TimeUnit.SECONDS)){
                    Thread.sleep(2000);
                    System.out.println(Thread.currentThread().getName() + " after try lock");
                } else {
                    System.out.println(Thread.currentThread().getName() + " try lock fail");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(lock.isHeldByCurrentThread()){
                    System.out.println(Thread.currentThread().getName()+" unlock");
                    lock.unlock();
                }
            }
        }, "third thread");

        t1.start();
        t2.start();
        t3.start();
    }
}
